package top.laoshuzi.android.iotcamera.camera.respository

import com.alibaba.fastjson.JSON
import io.reactivex.Observable
import org.eclipse.paho.client.mqttv3.MqttClient
import top.laoshuzi.android.iotcamera.camera.CameraConstants
import top.laoshuzi.android.iotcamera.camera.bean.dto.CameraTargetCmdDTO
import top.laoshuzi.android.iotcamera.camera.bean.dto.LightStateCmdDTO
import top.laoshuzi.android.iotcamera.core.network.utils.MqttUtils
import top.laoshuzi.android.iotcamera.camera.bean.dto.CameraTargetDTO

class CameraResposity(private val mqttClient: MqttClient) {

    init {
        mqttClient.connect(MqttUtils.mqttConfig())
    }

    fun publishCameraControlDirection(cameraTargetDTO: CameraTargetDTO) {

        val angularRange = IntRange(0, 180)
        if (!angularRange.contains(cameraTargetDTO.angular))
            throw RuntimeException("角度范围越界")

        val angularData = 500 + 2000 * cameraTargetDTO.angular / 180

        val angularLowBit = angularData.and(0xff)
        val angularHightBit = angularData.shr(8).and(0xff)

        val cmd1 = CameraTargetCmdDTO().apply {
            serial_data = listOf(
                0xff,
                0x1,
                cameraTargetDTO.num,
                cameraTargetDTO.angularVelocity,
                0x0
            )
        }

        val cmd2 = CameraTargetCmdDTO().apply {
            serial_data = listOf(
                0xff,
                0x2,
                cameraTargetDTO.num,
                angularLowBit,
                angularHightBit
            )
        }

        mqttClient.publish(
            CameraConstants.TOPIC_CAMERA_TARGET_SET.replace("{id}", cameraTargetDTO.deviceId),
            MqttUtils.mqttMessage(JSON.toJSONString(cmd1), 0, false)
        )

        mqttClient.publish(
            CameraConstants.TOPIC_CAMERA_TARGET_SET.replace("{id}", cameraTargetDTO.deviceId),
            MqttUtils.mqttMessage(JSON.toJSONString(cmd2), 0, false)
        )
    }

    fun publishLightState(id: String, lightStateCmdDTO: LightStateCmdDTO) {
        mqttClient.publish(
            CameraConstants.TOPIC_LIGHT_SET.replace("{id}", id),
            MqttUtils.mqttMessage(JSON.toJSONString(lightStateCmdDTO), 0, false)
        )
    }

    fun subscribeLightState(id: String): Observable<LightStateCmdDTO> {
        return Observable.create<LightStateCmdDTO> { e ->
            mqttClient.subscribeWithResponse(
                CameraConstants.TOPIC_LIGHT_GET.replace("{id}", id),
                0
            ) { topic, message ->
                val payload = MqttUtils.mqttPayload(message)
                e.onNext(JSON.parseObject(payload, LightStateCmdDTO::class.java))
            }
        }

    }

    fun unsubscribeLightState(id: String) {
        mqttClient.unsubscribe(CameraConstants.TOPIC_LIGHT_GET.replace("{id}", id))
    }

}